package com.ljchen.formalProject.frame.shiro.jwt;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.ljchen.formalProject.enums.ResultCode;
import com.ljchen.formalProject.frame.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Slf4j
public class JwtFilter extends BasicHttpAuthenticationFilter {

    /**
     * 跨域处理
     *
     * @param request  请求
     * @param response 响应
     * @return boolean
     * @throws Exception 异常
     */
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = WebUtils.toHttp(request);
        HttpServletResponse httpServletResponse = WebUtils.toHttp(response);
        httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
        // 跨域时会首先发送一个OPTIONS请求，这里我们给OPTIONS请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return false;
        }
        return super.preHandle(request, response);
    }

    /**
     * 是否访问允许
     * 这边看业务要求来决定是否返回false；如果返回false的话，则不会执行登录操作
     *
     * @param request     请求
     * @param response    响应
     * @param mappedValue 映射值
     * @return boolean
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        if (isLoginAttempt(request, response)) {
            try {
                executeLogin(request, response);
                return true;
            } catch (Exception e) {
                String message = e.getMessage();
                Throwable throwable = e.getCause();
                //捕获token错误
                if (throwable instanceof SignatureVerificationException) {
                    message = "Token不正确" + throwable.getMessage();
                }
                //捕获token过期
                else if (throwable instanceof TokenExpiredException) {
                    message = "Token已过期" + throwable.getMessage();
                }
                //碰到其余错误
                else {
                    if (throwable != null) {
                        message = throwable.getMessage();
                    }
                    this.response401(response, message);
                    return false;
                }
            }
        } else {
            HttpServletRequest httpServletRequest = WebUtils.toHttp(request);
            //获取请求方式
            String requestMethod = httpServletRequest.getMethod();
            //获取请求地址
            String requestURI = httpServletRequest.getRequestURI();
            log.info("请求方式{} Token为空 API接口地址为{}", requestMethod, requestURI);
            //这边是否返回false要根据具体的业务来确定（如果业务设定为只有用户登录之后才能访问接口的话，则返回false）
//            return false;
        }
        return true;
    }

    /**
     * isAccessAllowed返回false的话会执行这个方法
     *
     * @param request  请求
     * @param response 响应
     * @return boolean
     * @throws Exception 异常
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        this.sendChallenge(request, response);
        return false;
    }

    /**
     * 校验Header中是否存在Authorization这个字段，如果这个字段不为空，则说明当前用户想要登录
     *
     * @param request  请求
     * @param response 响应
     * @return boolean
     */
    @Override
    protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {
        String token = this.getAuthzHeader(request);
        if (StrUtil.isNotEmpty(token)) {
            return true;
        }
        return false;
    }

    /**
     * 执行登录
     *
     * @param request  请求
     * @param response 响应
     * @return boolean
     * @throws Exception 异常
     */
    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
        String token = this.getAuthzHeader(request);
        if (StrUtil.isNotEmpty(token)) {
            token = token.replace("Bearer ", "");
        }
        JwtToken jwtToken = new JwtToken(token);
        Subject subject = this.getSubject(request, response);
        subject.login(jwtToken);
        return true;
    }

    /**
     * 返回错误信息
     *
     * @param response 响应
     * @param message  消息
     */
    private void response401(ServletResponse response, String message) {
        HttpServletResponse httpServletResponse = WebUtils.toHttp(response);
        httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json;charset=utf-8");
        try {
            log.error("===========response401{}========>", message);
            PrintWriter printWriter = response.getWriter();
            String data = JSONObject.toJSONString(Result.error(ResultCode.ERROR_401, "没有权限访问" + message));
            printWriter.append(data);
        } catch (IOException e) {
            log.error("JwtFilter::401 Error", e);
        }
    }
}
